﻿using System;
using System.IO.Packaging;
using System.Linq;
using System.Xml.Linq;

namespace Songhay.OpenXml
{
    using Songhay.Xml;

    /// <summary>
    /// Static members for Open XML.
    /// </summary>
    public static partial class OpenXmlUtility
    {
        /// <summary>
        /// Converts the Open Packaging Conventions (OPC) file to “flat OPC.”
        /// </summary>
        /// <param name="path">The path.</param>
        /// <remarks>
        /// For details, see “Transforming Open XML Documents to Flat OPC Format”
        /// by Eric White
        /// (http://blogs.msdn.com/b/ericwhite/archive/2008/09/29/transforming-open-xml-documents-to-flat-opc-format.aspx)
        /// 
        /// “Note that the Flat OPC format is not the same
        /// as the ‘Word 2003 XML Document’ format.
        /// Those documents have a schema
        /// that is very different from the Flat OPC format.”
        /// —Eric White
        /// “The Flat OPC Format”
        /// (http://blogs.msdn.com/b/ericwhite/archive/2008/09/29/the-flat-opc-format.aspx)
        /// </remarks>
        /// <returns></returns>
        public static XDocument TransformOpcToFlat(string path)
        {
            var getProcessingInstruction =
                new Func<string, XProcessingInstruction>(
                    (pathToPackage) =>
                    {
                        if(pathToPackage.ToLower().EndsWith(".docx"))
                            return new XProcessingInstruction("mso-application",
                                        "progid=\"Word.Document\"");
                        if(pathToPackage.ToLower().EndsWith(".pptx"))
                            return new XProcessingInstruction("mso-application",
                                        "progid=\"PowerPoint.Show\"");
                        return null;
                    });

            using(Package package = Package.Open(path))
            {
                XDeclaration declaration = XObjectUtility.GetXDeclaration();
                XDocument doc = new XDocument(
                    declaration,
                    getProcessingInstruction.Invoke(path),
                    new XElement(NamespaceXmlPackage + "package",
                        new XAttribute(XNamespace.Xmlns + "NamespaceXmlPackage", NamespaceXmlPackage.ToString()),
                        package.GetParts().Select(part => GetPartContentsAsXml(part))
                    )
                );
                return doc;
            }
        }
    }
}
